/*
 * Endless Code License
 * Copyright (C) 2009 Jingul, Kim
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "ecContext.h"

jboolean JNICALL Java_ec_sys_Context_make(JNIEnv *env, jobject obj, jint handle) {
	jclass cls = env->GetObjectClass(obj);
	jfieldID hid = env->GetFieldID(cls, "context", "I");

	EC_CONTEXT *context = new EC_CONTEXT;
	EC_WND *wnd = (EC_WND*) handle;

	context->hDC = GetDC(wnd->hWnd);

	setDCPixelFormat(context);

	if (!(context->hRC = wglCreateContext(context->hDC))) {
		return JNI_FALSE;
	}

	if (!wglMakeCurrent(context->hDC, context->hRC)) {
		return JNI_FALSE;
	}

	env->SetIntField(obj, hid, (jint)context);

	return JNI_TRUE;
}

jboolean JNICALL Java_ec_sys_Context_release(JNIEnv *env, jobject obj) {
	EC_CONTEXT *context = getContext(env, obj);

	jboolean result = JNI_TRUE;

	if (!wglMakeCurrent(context->hDC, 0)) {
		return JNI_FALSE;
	}

	result = wglDeleteContext(context->hRC);

	return result;
}

void JNICALL Java_ec_sys_Context_swapBuffer(JNIEnv *env, jobject obj) {
	EC_CONTEXT *context = getContext(env, obj);

	SwapBuffers(context->hDC);
}

void setDCPixelFormat(struct EC_CONTEXT *context) {
	int nPixelFormat;

	static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be
			{ sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
					1, // Version Number
					PFD_DRAW_TO_WINDOW | // Format Must Support Window
							PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
							PFD_DOUBLEBUFFER, // Must Support Double Buffering
					PFD_TYPE_RGBA, // Request An RGBA Format
					32, // Select Our Color Depth
					0, 0, 0, 0, 0, 0, // Color Bits Ignored
					0, // No Alpha Buffer
					0, // Shift Bit Ignored
					0, // No Accumulation Buffer
					0, 0, 0, 0, // Accumulation Bits Ignored
					16, // 16Bit Z-Buffer (Depth Buffer)
					0, // No Stencil Buffer
					0, // No Auxiliary Buffer
					PFD_MAIN_PLANE, // Main Drawing Layer
					0, // Reserved
					0, 0, 0 // Layer Masks Ignored
			};

	nPixelFormat = ChoosePixelFormat(context->hDC, &pfd);

	SetPixelFormat(context->hDC, nPixelFormat, &pfd);
}

EC_CONTEXT* getContext(JNIEnv *env, jobject obj) {
	jclass cls = env->GetObjectClass(obj);
	jfieldID hid = env->GetFieldID(cls, "context", "I");

	return (EC_CONTEXT*) env->GetIntField(obj, hid);
}
